package com.zhike.utils;

import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhike
 * @CreateTime: 2024/2/1 14:09
 * @Description: 当前工具类可以适用于任何JDBC方式访问的数据中的任何查询语句
 */
public class JdbcUtils {
    public static <T> List<T> queryList(Connection connection, String sql, Class<T> clz, boolean underScoreToCamel) throws Exception {
        //创建一个List用于存储查询结果
        ArrayList<T> result = new ArrayList<>();

        //预编译sql
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        //获取查询结果的元数据
        ResultSetMetaData metaData = resultSet.getMetaData();
        //获取列字段
        int columnCount = metaData.getColumnCount();

        //对查询结果的行遍历
        while (resultSet.next()) {
            T t = clz.newInstance();
            for (int i = 0; i < columnCount; i++) {

                //获取属性名和属性值
                String columnName = metaData.getColumnName(i + 1);
                Object value = resultSet.getObject(columnName);

                //判断是否需要转换（下划线与驼峰）
                if (underScoreToCamel) {
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                }

                //赋值
                BeanUtils.setProperty(t, columnName, value);
            }
            result.add(t);
        }

        preparedStatement.close();
        resultSet.close();
        //返回List
        return result;
    }
}
